package com.markerhub.util;

import cn.hutool.core.map.MapUtil;
import com.markerhub.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
import io.jsonwebtoken.impl.DefaultJwtBuilder;
import lombok.Data;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "markerhub.jwt")
@Data
public class JwtUtils {
    private String secret;
    private long expire;
    private String header;
    @Autowired
    private DefaultJwtBuilder defaultJwtBuilder;
    /**
     * 生成jwt token
     */
    public String generateToken(User user) {
        Map<String, Object> headerMap = MapUtil.<String,Object>builder()
                .put("alg", "HS256")
                .put("typ", "JWT")
                .put("header", header).map();/*设置Header*/
        Map<String, Object> claimsMap = MapUtil.<String, Object>builder()
                .put("sub", user.getId())/*设置用户Id*/
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("exp", System.currentTimeMillis()+expire).map();/*设置Claims*/
        byte[] key = DatatypeConverter.parseBase64Binary(secret);/*生成key*/

        String jwt = defaultJwtBuilder
                .setHeader(headerMap)
                .setClaims(claimsMap)
                .signWith(SignatureAlgorithm.HS256, key).compact();/*生成jwt*/
        return jwt;
    }

    // 获取jwt的信息
    public  Claims getClaimByToken(String jwt) {
        return Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(secret))
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
